package server;

import java.sql.Connection;
import java.sql.CallableStatement;
import java.sql.DriverManager;
// import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBConnector {
	private String DB_ADDR = "localhost";
	private String DB_USER = "root";
	
	// Sergey's DB
	// private String DB_PSW = "servas1986";

	// Shahaf's DB
	// private String DB_PSW = "root";
	
	// Shlomi's DB
	private String DB_PSW = "1234";
	
	public DBConnector(String db_addr, String db_user, String db_psw){
		if (db_addr != null)
	    	this.DB_ADDR = db_addr;
	    if (db_user != null)
	    	this.DB_USER = db_user;
	    if (db_psw != null)
	    	this.DB_PSW = db_psw;
	    
		try {
	        Class.forName("com.mysql.jdbc.Driver").newInstance();
	    } catch (Exception ex) {/* handle the error*/}
	}
	
	public Connection openConn(){
		try {
			Connection conn = DriverManager.getConnection("jdbc:mysql://"+DB_ADDR+"/icm",DB_USER,DB_PSW);
			return conn;
     	}
        catch (SQLException ex){/* handle any errors*/
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
     	}
		return null;
	}
	
	public void closeConn(Connection conn){
		try {
			conn.close();
		} catch (SQLException e) {}
	}
	
	public ResultSet runQuery(Query qry, Connection conn){
		// Statement stmt;		
		CallableStatement cs;
		
		try {
			cs = conn.prepareCall("{" + qry.getQuery() + "}");
			// stmt = conn.createStatement();
			if (qry.getExecst() == true){
				// ResultSet rs = stmt.executeQuery(qry.getQuery());
				ResultSet rs = cs.executeQuery();
				return rs;
			}
			// stmt.executeUpdate(qry.getQuery());
			cs.executeUpdate();
			return null;
		}
		catch (SQLException e){}
		return null;
	}
}
